/**
 * Created by user on 2015/9/22.
 */

var moment = require('moment');
var async = require('async');
var Activity = mongoose.model('activity_community');
var Partaker = mongoose.model('activity_community_partake_info');
var Share = mongoose.model('mobile_app_share_content');
var toolUtil = require('../../../common/utils/toolUtil');

exports.activityListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = body;
    //var sortType = paged ? {endDate:-1} : {};
    option.isValid = true;
    if (option.title) option.title = new RegExp(body.title);
    if (option.type) option.type = body.type;

    if (body.beginDate || body.endDate) {
        if (body.beginDate && body.endDate) {
            if (body.beginDate < body.endDate) {
                option.startDate = {$gte: body.startDate};
                option.endDate = {$lte: body.endDate};
            }
        } else if (body.beginDate) {
            option.beginDate = {$gte: body.beginDate};
        } else if (body.endDate) {
            option.endDate = {$lte: body.endDate};
        };
    };


    logger.debug(option);
    async.series([

        function (callbackInner) {
            Activity.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            Activity.find(option)
                //.populate('province', '_id name')
                //.populate('city', '_id name')
                //.populate('county', '_id name')
                .sort({endDate:-1}).skip(index).limit(size).exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {

                        async.eachSeries(results, function (activity, callbackInner2) {

                            //results.forEach(function (data) {
                            //    data.images.forEach(function (img) {
                            //        img.imageURL = "http://" + imgHost + img.imageURL;
                            //    });
                            //    data._doc.url = activityUrl + '?activityId=' + data._id;
                            //
                            //});
                            for(img in activity.images) {
                                img.imageURL = "http://" + imgHost + img.imageURL;
                            };
                            activity._doc.url = activityUrl + '?id=' + activity._id;

                            Partaker.count({activity:activity._id}, function (err, count) {

                                if (err) {
                                    callbackInner2(err, null);
                                }else {
                                    //var temp = {count: count, totalPage:Math.ceil(count/size)};
                                    activity._doc.partakerCount = count;
                                    callbackInner2(err, activity);
                                }
                            });
                            //callbackInner2(err, activity)
                        }, function (err) {
                            callbackInner(err,results);
                        });
                        //callbackInner(null, results);
                    }
                });

        }], callback);

};


exports.activityAddService = function(req ,callback) {

    var body = req.body;
    //logger.debug(body);

    var timestamp= new Date().getTime();

    var data = {
        title : body.title
        ,desc : body.desc
        ,shareKey : timestamp
        ,shareDesc :  body.shareDesc
        ,type : body.type
        ,explain: body.explain
        ,address: body.address
        ,charge : body.charge
        ,beginDate : body.beginDate
        ,endDate : body.endDate
    };

    //if (body.provinceId)  data.province = body.provinceId;
    //if (body.cityId)  data.city = body.cityId;
    //if (body.countyId)  data.county = body.countyId;
    if (body.images) data.images = body.images;
    if (body.shareImage) data.shareImage = body.shareImage;

    logger.debug(data);

    var temp = new Activity(data);
    temp.save(function(err, result){

        var share = new Share();
        share.key = timestamp;
        share.title = body.title;
        share.desc = body.shareDesc;
        share.image = body.shareImage;
        share.url = activityUrl+ '?id=' + temp._id;

        share.save(function(err, result) {
            callback(err, result);
        });

    });




};

exports.activityDeleteService = function (req, callback) {

    var ids = req.body.activityID;

    var queryIn = {};
    queryIn["$in"] = [];
    for (var i = 0, l = ids.length; i < l; i++) {
        queryIn["$in"].push(ids[i]);
    }
    logger.debug(queryIn);
    Activity.update({_id:queryIn}, {isValid: false},{ multi: true }, callback);
};

exports.activityEditService = function(req ,callback) {
    var body = req.body;
    var id = req.body.id;
    var activity = req.body.activity;
    if (!(id && activity))  return callback('body错误', null);
    logger.debug(req.body);

    var data ={};
    if (activity.title) data.title = activity.title;
    if (activity.shareImage) data.image = activity.shareImage;
    if (activity.shareDesc) data.desc = activity.shareDesc;

    logger.debug(activity.shareKey);
    logger.debug(data);
    Share.update({key: activity.shareKey}, data, function(err) {
        Activity.update({_id:id}, activity, callback);
    });

};

exports.partakerListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = body;
    //var sortType = paged ? {endDate:-1} : {};

    //if (option.name) option.name = new RegExp(option.name);
    logger.debug(option);

    async.series([

        function (callbackInner) {
            Partaker.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            Partaker.find(option).populate('user', '_id nickName')
                .sort({dateCreated:-1}).skip(index).limit(size).exec(function (err, results) {
                    if (err) {
                        callbackInner(err);
                    } else {
                        callbackInner(null, results);
                    }
                });

        }], callback);

};

exports.exportPartakerService = function (req, callback) {

    var input = req.cparams;
    logger.debug(input);
    logger.debug(input.ids);
    var option = {};
    var ids = input.ids.split(',');

    var queryUserIn = {};
    queryUserIn["$in"] = [];
    for (var i = 0, l = ids.length; i < l; i++) {
        queryUserIn["$in"].push(ids[i]);
    };
    option["activity"] = queryUserIn;
    logger.debug(option);
    //opt.partake = {$exists: true, $not: {$size: 0}};

    //var opt = {activity:'63a0be9fce7d8b01169144c'};

    async.series([
        function (callbackInner) {
            Partaker.find(option)
                .populate('community', '_id communityName')
                .populate('user', '_id community userType nickName')
                .sort({dateCreated: -1})
                .exec(function (err, result) {
                    callbackInner(err, result);
                });
        }
    ], callback);
};

exports.activityPushService = function (req, callback){

    var body = req.body;

    //var size = 1000;

    async.series([
        function (callbackInner) {
            var option = {
                activity: body.activityId
            };

            Partaker.find(option)
                .populate('user', '_id community huanxinUserName')
                .populate('community', '_id communityName')
                .exec(function (err, result) {

                async.eachSeries(result, function (user, callbackInner2) {

                    logger.debug(user.user);
                    user.user.community._id = user.user.community;
                    toolUtil.pushCustomerServiceMessage(user.user, body.desc);
                    //logger.debug(user);
                    callbackInner2();

                    //var key = 'user:' + temp.user + ':app:data:statistic';
                    //var opt = [ key,'question', 'questionReply', 'praise', 'goods'];
                    //redisClient.hmget(opt, function (err, result) {
                    //    temp._doc.questionCount = result[0] ? result[0]:0;
                    //    temp._doc.replyCount = result[1] ? result[1]:0;
                    //    temp._doc.praiseCount = result[2] ? result[2]:0;
                    //    temp._doc.goodsCount = result[3] ? result[3]:0;
                    //    callbackInner(err, temp);
                    //});

                }, function (err) {
                    callbackInner(err, result);
                });
            });
        }
    ], callback);
    //callback();

    //Partaker.count(option, function (err, count) {
    //
    //    if (err) {
    //        callback(err, null);
    //    }else {
    //        //var temp = {count: count, totalPage:Math.ceil(count/size)};
    //        var cycleCount = Math.ceil(count/size);
    //
    //        var index = 1;
    //        //var index = 0;
    //
    //        async.whilst(function () {
    //                return index <= cycleCount;
    //            },
    //            function (next) {
    //
    //                Partaker.find(option).sort({dateCreated:1}).skip((index-1)*size).limit(size).exec(function (err, results) {
    //                    //if (err) {
    //                    //    callbackInner(err);
    //                    //} else {
    //                    //    callbackInner(null, results);
    //                    //}
    //
    //                    index++;
    //                    next();
    //
    //                    logger.debug(index);
    //                });
    //            },
    //            function (err) {
    //                // All things are done!
    //                callback(err);
    //            });
    //    }
    //});
    //


    //async.waterfall([
    //
    //    function (callbackInner) {
    //        Partaker.count(option, function (err, count) {
    //
    //            if (err) {
    //                callbackInner(err, null);
    //            }else {
    //                //var temp = {count: count, totalPage:Math.ceil(count/size)};
    //                var cycleCount = Math.ceil(count/size);
    //                callbackInner(null, cycleCount);
    //            }
    //        });
    //    },
    //    function (cycleCount,callbackInner) {
    //
    //        var count = 1;
    //        var index = 0;
    //        async.whilst(function () {
    //                if(count <= cycleCount){
    //                    return count <= cycleCount;
    //                }else{
    //                    callbackInner()
    //                };
    //            },
    //            function (next) {
    //
    //                var index = index * size;
    //
    //                Partaker.find(option).sort({dateCreated:1}).skip(index).limit(size).exec(function (err, results) {
    //                        //if (err) {
    //                        //    callbackInner(err);
    //                        //} else {
    //                        //    callbackInner(null, results);
    //                        //}
    //
    //
    //                        count++;
    //                        index++;
    //                        next();
    //
    //                        logger.debug(index);
    //                });
    //            },
    //            function (err) {
    //                // All things are done!
    //            });
    //    }
    //    //,
    //    //function (result,callbackInner) {
    //    //
    //    //    if (!result) {
    //    //        var err = {
    //    //            "message": '没有用户参加活动'
    //    //        };
    //    //        callbackInner(err, null);
    //    //    } else {
    //    //        //每1000个用户推送一次
    //    //
    //    //
    //    //
    //    //    }
    //    //}
    //
    //
    //], callback);

};